package com.ittx.dzt.jinglyun.handler;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.jinglyun.util.JinglYunSignUtil;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 鲸灵云 平台API处理父类
 * <p>
 *
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/10/17
 */
@Slf4j
public abstract class AbstractBaseJinglYunApiHandler<T> extends AbstractBasePlatformApiHandler<T> {

	@Autowired
	protected RocketmqProducer rocketmqProducer;

	@Override
	public String getPlatformCode() {
		return PlatformConstant.JINGLYUN;
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param platformApiParamDTO 店铺配置
	 * @param paramMap            请求参数
	 * @param requestId           请求id
	 * @return 请求结果
	 */
	public Result executeApi(PlatformApiParamDTO platformApiParamDTO, Map<String, Object> paramMap, String requestId) {
		long timestamp = System.currentTimeMillis();
		// 发起请求
		Result result = null;
		try {
			result = fetch(platformApiParamDTO, paramMap, requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = JacksonTool.toMap(result.getData());
				Boolean status = MapUtil.getBool(resultMap, "status");
				if (!status) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getJinglMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(JacksonTool.toJson(result));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getJinglMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getJinglMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param platformApiParamDTO 店铺配置
	 * @param paramMap            请求参数
	 * @param requestId           请求id
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result<?> fetch(PlatformApiParamDTO platformApiParamDTO, Map<String, Object> paramMap, String requestId) throws IOException {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		//公共的请求参数
		paramMap.put("appId", storeConfig.getAppKey());
		paramMap.put("gmtRequest", System.currentTimeMillis());
		paramMap.put("randomStr", RandomUtil.randomString(20));
		paramMap.put("supplierDockId", storeConfig.getStoreUniqueCode());
		// String signStr = JinglYunSignUtil.generateSignString(paramMap) + "&key=" + storeConfig.getAppSecret();
		// log.debug("签名字符串：{}",signStr);
		String sign = JinglYunSignUtil.getSign(JSON.parseObject(JacksonTool.toJson(paramMap)), storeConfig.getAppSecret());
		// paramMap.put("sign", SecureUtil.md5(signStr).toUpperCase());
		paramMap.put("sign", sign);

		Map<String, String> headerMap = MapUtil.newHashMap();
		headerMap.put("user-agent", "ittx-cbl");

		String url = storeConfig.getSdkUrl() + this.getJinglMethod();
		HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);
		if (httpRequestTemplate == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
		}
		String postReqJson = JacksonTool.toJson(paramMap);
		log.debug("url:{},reqHeaderJson:{}, reqJson:{} ", url, JacksonTool.toJson(headerMap), postReqJson);
		String returnMsg = httpRequestTemplate.postJsonParamsHeader(url, postReqJson, headerMap);
		log.debug("returnMsg:{}", returnMsg);
		if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isTypeJSON(returnMsg)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
					, this.getJinglMethod(), url, returnMsg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
		}
		return Result.success().addData(returnMsg);
	}

	/**
	 * 获取平台方法名称
	 *
	 * @return
	 */
	public abstract String getJinglMethod();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public static Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public static void main(String[] args) {
		System.out.println(totalPage(21, 20));
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	/**
	 * 时间格式转换
	 */
	public String timeToString(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC);
		return df.format(localDateTime);
	}

	public String format(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
		return df.format(localDateTime);
	}

	/**
	 * 时间类型转换
	 */
	public String localDateTimeToString(LocalDateTime localDateTime) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return df.format(localDateTime);
	}
}
